class Cart {
    constructor() {
      this.axiosRes();
      this.getData();
      this.bindEve();
    }
    axios的拦截
    axiosRes() {
      // 添加响应拦截器
      axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        // console.log(response);
        if (response.data.code == 401) {
          location.assign('./login.html?returnUrl=./cart.html')
        }
        return response;
      }, function (error) {
        return Promise.reject(error);
      });
    }
  
  
    //获取数据渲染到购物车中
    async getData() {
      let userId = localStorage.getItem('user_id');
      //设置参数传递方式
      axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
      //发送ajax请求
      let { status, data } = await axios.get('http://localhost:8888/cart/list?id=' + userId);
      //判断服务器状态
      if (status != 200) return;
      //判断token是否过期
      //过期重新登陆,成功登录后返回购物车
      if (data.code == 0) {
        location.assign('./login.html?returnUrl=./cart.html')
      }
      //token没有过期 将数据添加到购物车中
      if (data.code == 1) {
        //渲染购物车列表数据
        let html = '';
        data.cart.forEach(ele => {
          // console.log(ele);
          html += ` <ul class="goods-list yui3-g" data-id=${ele.goods_id}>
              <li class="yui3-u-3-8 pr">
                  <input type="checkbox" class="good-checkbox">
                  <div class="good-item">
                      <div class="item-img">
                          <img src="${ele.img_small_logo
            }">
                      </div>
                      <div class="item-msg">${ele.title}</div>
                  </div>
              </li>
              <li class="yui3-u-1-8">
                  <span class="price">${ele.price}</span>
              </li>
              <li class="yui3-u-1-8">
                  <div class="clearfix">
                      <a href="javascript:;" class="increment mins">-</a>
                      <input autocomplete="off" type="text" value="1" minnum="1" class="itxt">
                      <a href="javascript:;" class="increment plus">+</a>
                  </div>
              </li>
              <li class="yui3-u-1-8">
                  <span class="sum">${ele.price * ele.cart_number}</span>
              </li>
              <li class="yui3-u-1-8">
                  <div class="del1">
                      <a href="javascript:;" class="del-goods">删除</a>
                  </div>
              </li>
          </ul>`
        });
  
        //追加到页面中
        this.$('.cart-list').innerHTML = html;
      }
    }
    bindEve() {
      //给全选按钮绑定点击事件
      this.$('.cart-th input').addEventListener('click', this.allCheck.bind(this))
  
      //给单个商品的共同父级绑定点击事件,实现事件委托
      this.$('.cart-list').addEventListener('click', this.choose.bind(this))
  
      this.$('.cart-list').addEventListener('input',this.changeNum.bind(this))
    }
    //检测点击的是哪个
    choose(ele) {
      //获取事件源
      let tar = ele.target;
      // console.log(tar);
      if (tar.classList.contains('good-checkbox')) {
        this.manageOG(tar);
        //统计数量和价格
        this.totalSP();
      }
      //判断点击的是否是删除
      if (tar.classList.contains('del-goods')) {
        this.delGoods(tar);
      }
      //判断点击的是否是+或-
      if(tar.classList.contains('plus')||tar.classList.contains('mins')){
        this.changeNum(ele);
      }
    }
  
  
    // 全选的实现
    allCheck(ele) {
      // console.log(ele.target);
      let status = ele.target.checked;
      // console.log(status);
      this.setOneCheck(status);
      this.totalSP();
      if(!status){
        this.totalSP() ;
      }
    }
  
    //设置单个的状态
    setOneCheck(status) {
      let oneGoods = document.querySelectorAll('.good-checkbox')
      // console.log(oneGoods);
      oneGoods.forEach(ele => {
        ele.checked = status;
        // console.log(ele,ele.checked);
      })
    }
  
    //单个商品都被选中时,全选按钮也选上
    manageOG(tar) {
      // console.log(tar, tar.checked);
      if (tar.checked) {
        let oneGoods = document.querySelectorAll('.good-checkbox');
        // console.log(oneGoods);
        //oneGoods是个伪数组,转化为真数组
        let res = [...oneGoods].some(ele => {
          return !ele.checked;
        })
        if (!res) this.$('.cart-th input').checked = true;
      } else {
        this.$('.cart-th input').checked = false;
      }
    }
  
  
    //统计数量和总价
    totalSP() {
      //商品数量和小计
      let goodsNum = 0;
      let goodsPrice = 0;
      //只统计选中的商品数量和价格
      let goodList = document.querySelectorAll('.goods-list');
      // console.log(goodList);
      goodList.forEach(ul => {
        let checkbox = this.getChildren(ul, '.good-checkbox', 'checked');
        // console.log(checkbox);
        if (checkbox) {
          let num = this.getChildren(ul, '.itxt', 'value') - 0;
          let sum = this.getChildren(ul, '.sum', 'innerHTML') - 0;
          // console.log(checkbox,num,sum);
          goodsNum += num;
          goodsPrice += sum;
          this.$('.summoney').innerHTML = goodsPrice.toFixed(2);
          this.$('.sumprice-top strong').innerHTML = goodsNum;
        }
  
      })
    }
  
  
    //删除的实现
    delGoods(tar) {
      let readyDel = this.deep(tar);
      //  console.log(readyDel);
      //  console.log(this);
      let that = this;
      console.log(that);
      layer.msg('确定残忍的抛弃奴家吗?', {
        time: 20000, //20s后自动关闭
        btn: ['确定', '取消'],
        yes(index) {
          layer.close(index);
          // console.log(11111);
          //获取商品id和用户id,删除ul
          let userId = localStorage.getItem('user_id');
          let goodsId = readyDel.dataset.id;
          let token = localStorage.getItem('token');
          // console.log(userId,goodsId,token);
          //发送ajax请求
          axios.defaults.headers.common['Authorization'] = token;
          axios.get('http://localhost:8888/cart/remove?id=' + userId + '&goodsId=' + goodsId).then(({ status, data }) => {
            //判断服务器状态和接口状态
            if (status == 200 && data.code == 1) {
              // console.log(this);
              readyDel.remove();
              that.getChildren(readyDel, '.good-checkbox', 'checked') && that.totalSP();
            }
          })
        }
      });
    }
     
     //点击‘+’‘-’修改数量的实现
     changeNum(ele){
      if(ele.target.type=='checkbox') return;
      // console.log(ele);
      let input = '';
      let val = 0;
      if(ele.type=='input'){
        input = ele.target;
        val = input.value-0
        if(val<1){
          val = 1;
        }
        input.value = val;
      }
      if(ele.type=='click'){
        let mark = ele.target.innerHTML;
        // console.log(mark);
        if(mark=='+'){
          input = ele.target.previousElementSibling;
          // console.log(input);
          val = input.value-0+1;
        }
        if(mark=='-'){
          //获取input框
          input = ele.target.nextElementSibling;
          val = input.value-1;
          if(val<1) val = 1;
        }
        input.value = val ;
      }
      this.sumPrice(val,ele.target);
     }
      
  
     //小计的实现
  
     sumPrice(val,target){
        // console.log(val);
        // console.log(target);
        // console.log(this);
        //找最大的父级ul
        let ul = this.deep(target);
        // console.log(ul);
        //获取单价
        let price = this.getChildren(ul,'.price','innerHTML');
        //获取数量
        let sum = ul.querySelector('.sum')
        // console.log(sum);
        sum.innerHTML = (val*price).toFixed(2);
  
        //发送ajax请求改变商品数量
        let goodsId = ul.dataset.id;
        this.sendAjaxNum(goodsId,val);
        this.totalSP();
     }
  
        //利用防抖,减少向服务器发送请求的次数
        //修改服务器数量
        times = '';
        sendAjaxNum(goodsId,val){
          clearTimeout(this.times);
         this.times = setTimeout(()=>{
          axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
          axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
          let userId = localStorage.getItem('user_id');
          axios.post('http://localhost:8888/cart/number=id'+userId+'&goodsId'+val).then(res=>{
            // console.log(res);
          })
         },300)
        }
  
  
    //获取父节点下的某个子节点
    getChildren(father, children, attr = 'value') {
      return father.querySelector(children)[attr];
    }
    // 获取节点的方法
    $(ele) {
      let res = document.querySelectorAll(ele);
      return res.length == 1 ? res[0] : res;
    }
  
    //递归找到父级ul
    deep(ele, tar = 'ul') {
      if (ele.nodeName == tar.toUpperCase()) {
        // 结果返回到   return this.deep(ele.parentNode) (内部调用)
        return ele;
      }
      // return 结束代码执行,虽然下方代码被调用多次,但是return没有返回,因为后面有函数
      // 当函数执行完成,return只返回一次,就结束代码执行
      return this.deep(ele.parentNode)
    }
  }
  
  new Cart;